<?php

namespace app\speedDating\services\common;

use app\speedDating\exception\JWTExpiredException;
use app\speedDating\exception\JWTValidateException;
use app\speedDating\interfaces\ServiceCode;
use app\speedDating\interfaces\ServiceStatus;
use app\speedDating\interfaces\ServiceMsgText;
use app\speedDating\model\SddUser;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class JWTService
{
    /**
     * 创建JWT访问令牌
     * @param $user
     * @return array
     */
    public static function authorizations($user): array
    {
        $key = env('JWT_KEY', 'wPMbcOdAduaFahx=');
        $time = time();
        $token = [
            'iat' => $time,
            'main' => [
                'u_id' => $user['id'],
                'u_name' => $user['username']
            ]
        ];

        $access_token = $token;
        $access_token['scopes'] = 'role_access';
        $access_token['exp'] = $time + (86400 * 7);

        $refresh_token = $token;
        $refresh_token['scopes'] = 'role_refresh';
        $refresh_token['exp'] = $time + (86400 * 30);

        return [
            'access_token' => JWT::encode($access_token, $key, 'HS256'),
            'refresh_token' => JWT::encode($refresh_token, $key, 'HS256'),
            'token_type' => 'bearer'
        ];
    }

    /**
     * JWT校验
     * @param $authorization
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function verify($authorization): array
    {
        $key = env('JWT_KEY', 'wPMbcOdAduaFahx=');
        $jwt = self::parseAuthBearer($authorization);
        try {
            $jwtData = JWT::decode($jwt, new Key($key, 'HS256'));
        } catch (ExpiredException $e) {
            throw  new JWTExpiredException($e->getMessage());
        } catch (\Exception $e) {
            throw  new JWTValidateException($e->getMessage());
        }
        $user = SddUser::getSimpleMainByID($jwtData->main->u_id);
        if (empty($user)){
            throw  new JWTValidateException(ServiceMsgText::ERR_VALIDATE_MEMBER_NOT_EXIST,ServiceCode::ERR_JWT);
        }
        if ($user->is_banned != ServiceStatus::STATUS_USER_USE){
            throw  new JWTValidateException(ServiceMsgText::ERR_UNAUTHORIZED_DISABLED,ServiceCode::ERR_JWT);
        }

        return (array)$jwtData->main;
    }

    /**
     * 放弃bearer 提取jwt字符
     * @param $authorization
     * @return false|string
     */
    public static function parseAuthBearer($authorization): string
    {
        return substr($authorization, 7);
    }


}